<template>
	<div class="related">
		<div class="main-search">
			<el-form :model="queryParams" ref="queryForm" :inline="true"
					 label-width="114px">
				<el-form-item label="知识点序号" prop="knowledgePointsNo">
					<el-input
						v-model="queryParams.knowledgePointsNo"
						placeholder="请输知识点序号"
						clearable
						style="width: 200px"
						@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="关联题目ID" prop="exercisesNo">
					<el-input
						v-model="queryParams.exercisesNo"
						placeholder="关联题目ID"
						clearable
						style="width: 200px"
						@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item prop="course">
					<aselect @clear="courseReturn" @change="courseReturn" :showBtn="true" title="关联课程" :course="DTOS"></aselect>
				</el-form-item>

				<el-form-item label="考试频度" prop="frequencys">
					<el-select multiple style="width: 200px" v-model="queryParams.frequencys">
						<el-option
							v-for="(item, index) in frequencyList"
							:key="index"
							:label="item.value"
							:value="item.key"
						/>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button :icon="Search" type="primary" @click="handleQuery">搜索</el-button>
				</el-form-item>
			</el-form>
		</div>

		<div class="main-search">
			<!-- 遍历当前选中考频对应的所有知识点 -->
			<div class="ms-item" v-for="(item, index) in related" :key="index">
				<div class="tag-select-container">
					<el-check-tag
						:checked="item.checked"
						@change="toggleActive(item)"
						style="padding: 16px; "
						type="primary"
					>
						{{ item.name }}
					</el-check-tag>

					<!-- 层级选择器：仅在当前标签被选中且是题目类型时显示 -->
					<el-select
						v-if="activeValues.includes(item.value) && actionType === 'question'"
						v-model="levelMap[item.value]"
						@change="(newLevel) => handleLevelChange(item, newLevel)"
						placeholder="应用层级"
						style="width: 100px; margin: 0 10px;"
					>
						<el-option
							v-for="level in levelOptions"
							:key="level.value"
							:label="level.label"
							:value="level.value"
						/>
					</el-select>
					<span
						v-if="activeValues.includes(item.value) && actionType === 'question'"
					>
						推题权重：
					</span>
					<el-slider
						v-if="activeValues.includes(item.value) && actionType === 'question'"
						v-model="weightMap[item.value]"
						@change="(newWeight) => handleWeightChange(item, newWeight)"
						:step="10"
						show-stops
						style="width: 120px; margin-left: 10px"
					/>
				</div>
			</div>
<!--			<el-pagination
				:total="total"
				v-model:page="queryParams.pageNum"
				v-model:limit="queryParams.pageSize"
				@pagination="handleQuery"
			/>-->
			<el-pagination
				v-model:current-page="queryParams.pageNum"
				:page-size="queryParams.pageSize"
				:total="total"
				background
				layout="total, prev, pager, next, jumper"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>

		</div>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
import aselect from '../../common/aselect/index.vue';
import { selectKnowledgePoints,addOrDeleteRelationship } from '/@/api/knowledge/index';

let DTOS = ref([{}]);
// 接收父组件传递的类型参数
const props = defineProps({
	actionType: {
		type: String,
		default: ''
	},
	DTOS: {
		type: Array,
		default: () => []
	},
	frequencyList: {
		type: Array,
		default: () => []
	},
	current: {
		type: Object,
		default: {

		}
	}
});

const total = ref(0);
// 相关知识点数据（按考频分类存储）
const related = ref([]);
const form = reactive({
	"fValue": [1]
});
// 查询参数（fValue存储选中的考频值数组）
const queryParams = reactive({
	"courseChapterNo": "",
	"courseNo": "",
	"courseSectionNo": "",
	"exercisesNo": "",
	"frequencys": [],
	"knowledgePointsNo": "",
	"pageNum": 1,
	"pageSize": 5,
	"pointsNo": props.current.pointsNo
});

// 选中项相关
const allSelectedItems = ref<Array<{
	label: string,
	value: string,
	level?: string,
	weight?: number
}>>([]);

// 计算属性：获取所有选中项的value集合
const activeValues = computed(() => allSelectedItems.value.map(item => item.value));

// 层级选择相关配置
const levelOptions = [
	{ label: 'A1', value: 'A1' },
	{ label: 'A2', value: 'A2' },
	{ label: 'A3', value: 'A3' },
	{ label: 'A4', value: 'A4' },
	{ label: 'A5', value: 'A5' }
];
const levelMap = ref<Record<string, string>>({});  // 存储每个知识点的层级
const weightMap = ref<Record<string, number>>({}); // 存储每个知识点的权重

// 定义emit事件
const emit = defineEmits(['selected', 'levelChange']);


// 切换标签选中状态
const toggleActive = async (item: object) => {
	await addOrDeleteRelationship(props.current.knowledgePointsNo, item.knowledgePointsNo);
	await handleQuery()
};

// 层级变化时更新
const handleLevelChange = (item: { label: string, value: string }, newLevel: string) => {
	levelMap.value[item.value] = newLevel;
	// 更新选中项中的层级
	const targetItem = allSelectedItems.value.find(i => i.value === item.value);
	if (targetItem) {
		targetItem.level = newLevel;
	}
	emit('selected', allSelectedItems.value);
};

// 权重变化时更新
const handleWeightChange = (item: { label: string, value: string }, newWeight: number) => {
	weightMap.value[item.value] = newWeight;
	// 更新选中项中的权重
	const targetItem = allSelectedItems.value.find(i => i.value === item.value);
	if (targetItem) {
		targetItem.weight = newWeight;
	}
	emit('selected', allSelectedItems.value);
};
const handleQuery = async () => {
	related.value = [];
	let res = await selectKnowledgePoints(queryParams);
	let list = res.data.list.filter((item) => {return item.knowledgePointsNo!==props.current.knowledgePointsNo})
	related.value = list;
	total.value = res.data.total;
}
const courseReturn = (params) => {
	if (params) {
		let list = params.split(",");
		queryParams.courseSectionNo = list.length > 0?list[list.length - 1]:'';
	} else {
		queryParams.courseSectionNo = '';
	}
}
const handleSizeChange = async (val: number) => {
	queryParams.pageSize = val;
	related.value = [];
	await handleQuery();
}
const handleCurrentChange = async (val: number) => {
	queryParams.pageNum = val;
	related.value = [];
	await handleQuery();
}
onMounted(()=>{
	handleQuery()
})
</script>

<style scoped lang="scss">
.related {
	min-height: 500px;

	.ms-item {
		/*width: 50%;*/
		float: left;
		text-align: left;
		padding-left: 40px;
		margin-bottom: 30px;
		min-height: 400px;

		.tag-select-container {
			display: flex;
			align-items: center; // 标签和选择器垂直居中
		}
	}
	.ms-item_up {
		width: 100%;
		float: left;
		text-align: center;
	}
}
</style>
